var eap_sa_template = {
	init : function(tabId) {
		var templateId = $('[name="model.id"]', getActiveDom()).val();
		$('#tplPrivilegeCtn').load(g_base_site + '/espirit/eap/sa/privilege.show.html?tabId=' + tabId + '&templateId=' + templateId, function() {
			$('#tplPrivilegeCtn').removeClass('loading');
		});
		
		$form = $("div[name='_templateForm']");
		initValidate($form);
		
		$('[cmbname="model.defaultWebsite.id"]', getActiveDom()).on('select', function(event, ui) {
			var websiteId = Ognl.get(ui.item, 'id');
			var url = g_base_site + '/espirit/eap/sa/privilege.show.html?tabId=' + tabId + '&templateId=' + templateId + '&websiteId=' + websiteId;
			$('#tplPrivilegeCtn').load(url, function() {
				$('#tplPrivilegeCtn').removeClass('loading');
			});
		});
	},

	saveTempatePrivilege : function(btn) {
		var $btn = $(btn);
		if ($btn.hasClass("disabled")) {
			return;
		}
		$btn.addClass("disabled");
		$form = $("div[name='_templateForm']");
		
		if (!validateForm($form)) {
			return;
		} 
		ajaxSubmit($form, {
			data: {_resultCode:'$json'},
			success:function() {
				closeTabPage(null, true);
			}
		});
	},

	applyTemplate : function(isTemplate, tabId, successInfo) {
		var $curTab = getActiveDom();
		var templateId = $('[name="model.userTemplate.id"]', $curTab).val();
		var name = $('[name="model.name"]', $curTab).val();
		var $userId = $('[name="model.loginUser.id"]', $curTab);
		if ($userId.length == 0) {
			$userId = $('[name="model.id"]', $curTab);
		}
		var userId = $userId.val();
		addLoading($('#tplPrivilegeCtn'));
		$.ajax({
			url: g_base_site + '/espirit/eap/sa/privilege.applySelectedPrivileges.html',
			dataType:'json',
			data: {
				isTemplate: isTemplate,
				templateId: templateId,
				name: name,
				userId: userId,
				clearOldData: true,
				_resultCode: '$json'
			},
			success: function(privileges) {
				removeLoading($('#tplPrivilegeCtn'));
				
				if (privileges.error) {
					showError(privileges.error);
				} else {
					initPrivilege(tabId, privileges);
					showSuccess(successInfo);
				}
			}
		});
	},

	showFieldPrivilege : function(modelPrivilege, title) {
		var $curTab = getActiveDom();
		var userId = $('[name="model.id"]', $curTab).val();
		var url = g_base_site + '/espirit/eap/sa/privilege.showFieldPrivilege.html?userId=' + userId;
		var websiteId = $('[name="model.defaultWebsite.id"]', $curTab).val();
		if (websiteId) {
			url += '&websiteId=' + websiteId;
		}
		if (modelPrivilege) {
			url += '&modelPrivilege=true';
		}
		openMainTab(url, title);
	}
}